<?php
/**
 * Introduction: 分销逻辑
 * @author: 杨陈鹏
 * @email: yangchenpeng@cdlinglu.com
 */

namespace Common\Logic;

use Common\Model;

class DistributionLogic
{

    static public $model,$income_model;

    public function __construct()
    {

        self::$model = new Model\DistributionModel();

        self::$income_model = new Model\MemberIncomeRecordModel();

    }

    /**
     * Introduction: 插入数据
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function create($data)
    {

        if(!$data['uid'])
            return ['code' => 300, 'msg' => '缺少用户信息!'];

        if(!$data['goods_id'])
            return ['code' => 300, 'msg' => '缺少商品信息!'];

        $datas['uid']       = $data['uid'];
        $datas['goods_id']  = $data['goods_id'];
        $datas['create_time']  = NOW_TIME;

        if(self::$model->add($data))
            return ['code' => 200, 'msg' => '添加成功'];


        return ['code' => 300, 'msg' => '添加失败!'];

    }
    /**
     * Introduction: 列表
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function getData($where,$page,$nums,$uid)
    {

        $data = self::$model
                ->where($where)
                ->page($page,$nums)
                ->select();

        //获取商品分销比例
        $member_logic   =   new MemberLogic();

        $bonus = $member_logic::$apply_dis
            ->where(['uid' => $uid])
            ->getField('commission_rate');

        if(!$data)
        {

            if($page == 1)
                return ['code' => 200, 'msg' => '您还没购买过分销的商品!'];

            return ['code' => 200, 'msg' => '后面没有了!'];

        }

        $goods_info = [];

        $goods_logic = D('Common/Goods','Logic');

        foreach($data as $k => $v){

            $goods_data = $goods_logic::getOneData(['id' => $v['goods_id']],'id,title,bonus,is_distribution');
            $goods_info[$k] = $goods_data['data'];
            $goods_info[$k]['click_nums'] = $v['click_nums'];
            $goods_info[$k]['buy_nums'] = $v['buy_nums'];
            $goods_info[$k]['bonus']    =   $bonus;

        }

        return ['code' => 200, 'data' => $goods_info];


    }
    /**
     * Introduction: 账户统计
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function bonusTotal($uid)
    {

        $member_logic = D('Common/Member','Logic');

        //获取账户余额
        $balance = $member_logic::$model
                            ->where(['uid' => $uid])
                            ->field('balance,frozen')
                            ->find();

        //获取今日的收入
        $today_time = strtotime(date('Y-m-d',NOW_TIME).' 00:00:00');

        $where = 'uid='.$uid.' AND create_time >='.$today_time.' AND create_time <='.NOW_TIME;

        $today_time_income          = self::$income_model->where($where)->sum('nums');
        //获取上一周收入

        $pre_week_income_time       = NOW_TIME - (60 * 60 * 24 * 7);
        $where                      = 'uid='.$uid.' AND create_time >='.$pre_week_income_time.' AND create_time <='.NOW_TIME;
        $pre_week_income            = self::$income_model->where($where)->sum('nums');
        //获取历史收入
        $history_income             = self::$income_model->where(['uid' => $uid])->sum('nums');
        $data['balance']            = sprintf("%.2f", ($balance['balance'] / 100));
        $data['frozen']             = sprintf("%.2f", ($balance['frozen'] / 100));
        $data['use']                = sprintf("%.2f", (($balance['balance'] - $balance['frozen']) / 100));
        $data['today_time_income']  = sprintf("%.2f", ($today_time_income / 100));
        $data['pre_week_income']    = sprintf("%.2f", ($pre_week_income / 100));
        $data['history_income']     = sprintf("%.2f", ($history_income / 100));

        return ['code' => 200, 'data' => $data];

    }
    /**
     * Introduction: 收入记录明细
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function incomeHistory($uid,$page,$nums)
    {

        $data = self::$income_model
           // ->fetchSql(true)
                ->where(['uid' => $uid])
                ->order('create_time desc')
                ->page($page,$nums)
                ->select();


        if( !$data )
        {

            if( $page == 1 )
                return ['code' => 200, 'msg' => '您还没有收入哦!'];


            return ['code' => 200, 'msg' => '后面没有了!'];

        }

        $goods_logic = D('Common/Goods','Logic');

        foreach( $data as $k => $v ){

            $data[$k]['create_time'] = date('Y-m-d H:i:s',$data[$k]['create_time']);
            $data[$k]['nums']        = sprintf("%.2f", ($data[$k]['nums'] / 100));

            $goods_info         = $goods_logic::getOneData(['id' => $v['goods_id']],'id,title');
            $data[$k] = array_merge($data[$k],$goods_info['data']);

        }

        return ['code' => 200, 'data' => $data];


    }
    /**
     * Introduction: 分销提成
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function divided($order_id,$uid)
    {

        try{

            //获取订单信息
            $order_logic = new OrderLogic();
            //$goods_logic = new GoodsLogic();
            $member_logic = new MemberLogic();

            $order_info = $order_logic::detail($order_id,'id,uid');


            foreach($order_info['data']['extend'] as $k => $v){

                if($v['invitation']){

                    //获取分销商品的用户uid

                    $uid = $member_logic::$model
                        ->where(['invitation'=>$v['invitation']])
                        ->getField('uid');

                    //获取当前商品的提成比例
                    $bonus = $member_logic::$apply_dis
                        ->where(['uid' => $uid])
                        ->getField('commission_rate');
                    //$goods_logic::$model
                        //->where(['id' => $v['goods_id']])
                        //->getField('bonus');

                    //计算当前商品分成金额
                    $price = $v['pay_total'] * ($bonus / 100);

                    //将提成放入用户账户
                    $member_logic::$model
                        ->where(['uid' => $uid])
                        ->setInc('balance',$price);

                    $balance = $member_logic::$model
                        ->where(['uid' => $uid])
                        ->getField('balance');

                    $attr = '';

                    if($v['attr'])
                        foreach($v['attr'] as $val)
                            $attr = $val['name'].',';

                    $attr = rtrim($attr,',');

                    if($attr)
                        $attr = "($attr)";

                    $data['uid']        = $uid;
                    $data['goods_id']   = $v['goods_id'];
                    $data['nums']       = $price;
                    $data['banlance']   = $balance;
                    $data['description']= '商品: ['.$v['title'].$attr.']分销提成';
                    $data['create_time']= NOW_TIME;
                    //插入收入记录
                    self::$income_model->add($data);

                    //更新分销商品用户的分销购买数量
                    self::$model
                        ->where(['goods_id' => $v['goods_id'],'uid' => $uid])
                        ->setInc('buy_nums',1);


                }

            }

            //file_put_contents(RUNTIME_PATH.'/fencheng.log',json_encode($data));

        }catch (\Exception $e){

            file_put_contents(RUNTIME_PATH.'distr.log',$e->getMessage());

        }

    }

}